import React from 'react'
import { Text, View, Image, TouchableOpacity, ImageBackground } from 'react-native'
import { API, WINDOW } from '../Services'
import ImagePicker_mult from 'react-native-image-crop-picker'
import underscore from 'underscore'
import { Metrics } from '../Themes'
import LdImage from './LdImage'

export default class AddPhotoView_edit extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            selectedPhotos: [],//新增的图片，对象数组
            initialImage: this.props.initialImage ? this.props.initialImage.split(',') : [], //已存在的图片，字符串数组
            maxNum: 9,
        }
    }

    deletePhoto(index) {
        let selectedPhotos = this.state.selectedPhotos
        selectedPhotos.splice(index, 1)
        this.setState({
            selectedPhotos,
        })
    }
    rendPhotos(element, index) {
        return (
            <ImageBackground style={{ width: (Metrics.screenWidth - 48) / 3, height: (Metrics.screenWidth - 48) / 3, marginLeft: 12, marginBottom: 10 }} source={{ uri: element.path }} key={index} >
                <TouchableOpacity onPress={() => this.deletePhoto(index)} style={{ position: 'absolute', right: -10, top: -10, padding: 8 }}>
                    <Image source={require('../Images/close.png')}/>
                </TouchableOpacity>
            </ImageBackground>
        )
    }

    deletePhoto_initial(index) {
        let initialImage = this.state.initialImage
        initialImage.splice(index, 1)
        this.setState({
            initialImage,
        })
    }
    rendPhotos_initial(element, index) {
        return (
            <View key={index} style={{ width: (Metrics.screenWidth - 48) / 3, height: (Metrics.screenWidth - 48) / 3, marginLeft: 12, marginBottom: 10 }}>
                <LdImage
                    style={{ width: (Metrics.screenWidth - 48) / 3, height: (Metrics.screenWidth - 48) / 3 }}
                    url={element}
                />
                <TouchableOpacity onPress={() => this.deletePhoto_initial(index)} style={{ position: 'absolute', right: -10, top: -10, padding: 8 }}>
                    <Image source={require('../Images/close.png')} />
                </TouchableOpacity>
            </View>

        )
    }

    _selectPhoto() {
        let BUTTONS = ['拍摄', '从手机相册选择', '取消']
        WINDOW.showActionSheet(
            {
                title: '选择',
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
            },
            buttonIndex => {
                if (buttonIndex === BUTTONS.length - 1) {
                    return
                } else if (buttonIndex === 0) {
                    this._selectFromCamera()
                } else if (buttonIndex === 1) {
                    this._selectFromPhoto()

                }
            },
        )
    }
    _selectFromPhoto() {
        ImagePicker_mult.openPicker({
            mediaType: 'photo',
            multiple: true,
            maxFiles: 9,
            compressImageMaxWidth: 2100,
            compressImageMaxHeight: 2100,
            compressImageQuality: 0.4,
        }).then(images => {
            console.log(images);
            let selectedPhotos = this.state.selectedPhotos.concat(images)
            selectedPhotos = underscore.first(selectedPhotos, this.state.maxNum - this.state.initialImage.length)
            this.setState({
                selectedPhotos
            })
        });
    }
    _selectFromCamera() {
        ImagePicker_mult.openCamera({
            compressImageQuality: 0.3,
        }).then(image => {
            console.log(image);
            let selectedPhotos = this.state.selectedPhotos.concat(image)
            selectedPhotos = underscore.first(selectedPhotos, this.state.maxNum - this.state.initialImage.length)
            this.setState({
                selectedPhotos
            })
        });
    }

    _doUploadMeia = () => {
        console.log(this.state)
        if (!this.state.selectedPhotos.length && !this.state.initialImage.length) {
            return WINDOW.showToast('请上传图片或视频！')
        }
        // return
        if (!this.state.selectedPhotos.length) {
            //没有新增
            let imagePaths = this.state.initialImage.join(',')
            this.props.selectImageCallback(imagePaths)
        } else {
            //有新增
            this._uploadImage()
        }
         
    }

    //上传图片
    _uploadImage = () => {
        let imag = this.state.selectedPhotos
        let key = WINDOW.showToastLoad()
        API.uploadImage(imag).then((response) => {
            WINDOW.hideToast(key)
            const { ok, data } = response
            let file = data?.data
            if (ok && data.code === 1) {
                let imagePaths
                if (underscore.isArray(file)) {
                    let temArray = file.map((element) => element.filepath)
                    temArray = temArray.concat(this.state.initialImage)
                    imagePaths = temArray.join(',')
                    this.props.selectImageCallback(imagePaths)
                } else {
                    let  temArray = this.state.initialImage
                    temArray = temArray.concat([file.filepath])
                    imagePaths = temArray.join(',')
                    this.props.selectImageCallback(imagePaths)
                }
            } else {
                WINDOW.showToastError(data.msg || '请求失败！')
            }
        })
    }

    render() {
        return (
            <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap' }}>
                {this.state.initialImage.map(this.rendPhotos_initial.bind(this))}
                {this.state.selectedPhotos.map(this.rendPhotos.bind(this))}
                <TouchableOpacity onPress={this._selectPhoto.bind(this)}>
                    <Image source={require('../Images/fabu_icon_sahngchuan_nor.png')} style={{ marginLeft: 10, marginBottom: 10 }} />
                </TouchableOpacity>
                <Text style={{ color: 'gray', fontSize: 18, alignSelf: 'flex-end', marginLeft: 15, marginBottom: 10 }}>
                    {this.state.selectedPhotos.length + this.state.initialImage.length}/{this.state.maxNum}
                </Text>
            </View>
        )
    }
}
